import axios from "axios";
import { Toast } from "vant"
import router from "@/router/index"

const service = axios.create({
    baseURL: 'http://157.122.54.189:9083/',
    // api的base_url
    // withCredentials: true, // 跨域请求时是否发送cookies
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        if (localStorage.token) { //判断token是否存在
            config.headers.Authorization = localStorage.getItem("token");  //将token设置成请求头
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);
// response 拦截器
service.interceptors.response.use(
    res => {
        // console.log(res);
        const errStatusCode = /^4\d{2}$/
        if (errStatusCode.test(res.data.statusCode)) {
            // console.log(res);
            Toast("失败了哈");
        }
        //4.2 并且在用户信息验证伪造的情况下
        if (res.data.message == '用户信息验证失败') {
            localStorage.removeItem("token");
            localStorage.removeItem("id");
            Toast(res.data.message);
            setTimeout(() => {
                router.replace("/register");
            }, 800)
        }
        return res;
    },
    error => {
        return Promise.reject(error);
    }
);



// service.interceptors.response.use(res => {
//     // 4.1 400 错误情况下
//     const errStatusCode = /^4\d{2}$/
//     if (errStatusCode.test(res.data.statusCode)) {
//         Toast("失败了哈");


//     }
//     //4.2 并且在用户信息验证伪造的情况下
//     if (res.data.message == '用户信息验证失败') {


//         localStorage.removeItem("token");
//         localStorage.removeItem("id");
//         Toast(res.data.message);
//         router.replace("/register");
//     }
//     return res
// });

export default service;
